from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from models import Computer, Queue
import xml.etree.ElementTree as ET

def computer(request, name='foo'):

    # handle the gets, check for accept encoding later
    if request.method == 'GET':
        comp = get_object_or_404(Computer, name__iexact=name)
        return HttpResponse("You're looking at computer %s." % name)

    elif request.method == 'DELETE':
        comp = get_object_or_404(Computer, name__iexact=name)
        comp.delete()
        return HttpResponse("Computer %s deleted." % name)

    elif request.method == 'POST':

        # get the xml data
        try:
            elem = ET.fromstring(request.raw_post_data)
        except:
            return HttpResponse(status=400)

        # check to see if it already exists
        try:
            comp = Computer.objects.get(name__iexact=name)
            new_name = None
            for node in elem:
                tag_name = node.tag.lstrip('{http://cadac.sdsc.edu/schema/runtracker}')
                if(tag_name == 'URL'):
                    comp.url = node.text
                if(tag_name == 'OS'):
                    comp.os = node.text
                if(tag_name == 'Architecture'):
                    comp.arch = node.text
                if(tag_name == 'Description'):
                    comp.description = node.text
                if(tag_name == 'Name'):
                    new_name = node.text

            if new_name:
                if new_name.lower() != name:
                    return HttpResponse(status=400)

            comp.save()

        except:
            HttpResponse(status=400)

    elif request.method == 'PUT':
        try:
            # get the xml data
            strlen = request.META['CONTENT_LENGTH']
            xml_str = request.META['wsgi.input'].read(strlen)
            try:
                elem = ET.fromstring(xml_str)
            except:
                return HttpResponse(status=400)

            new_name = url = os = arch = description = None
            for node in elem:
                tag_name = node.tag.lstrip('{http://cadac.sdsc.edu/schema/runtracker}')
                if(tag_name == 'URL'):
                    url = node.text
                if(tag_name == 'OS'):
                    os = node.text
                if(tag_name == 'Architecture'):
                    arch = node.text
                if(tag_name == 'Description'):
                    description = node.text
                if(tag_name == 'Name'):
                    new_name = node.text

            if new_name.lower() != name:
                return HttpResponse(status=400)            
        
            new_comp = Computer.objects.create(name=new_name, url=url, 
                                               os=os, arch=arch, 
                                               description=description)
        
        except:
            HttpResponse(status=400)

    return HttpResponse(status=200)


def queue(request, compname, qname):

    # handle the gets, check for accept encoding later
    if request.method == 'GET':
        comp = get_object_or_404(Computer, name__iexact=compname)
        queue = get_object_or_404(Queue, name__iexact=qname, computer=comp.id)
        return HttpResponse("You're looking at queue %s on %s." % (qname, compname))

    elif request.method == 'DELETE':
        comp = get_object_or_404(Computer, name__iexact=compname)
        queue = get_object_or_404(Queue, name__iexact=qname, computer=comp.id)
        queue.delete()
        return HttpResponse("Queue %s deleted." % qname)

    elif request.method == 'POST':

        # get the xml data
        try:
            elem = ET.fromstring(request.raw_post_data)
        except:
            return HttpResponse(status=400)

        try:
            comp = get_object_or_404(Computer, name__iexact=compname)
            queue = get_object_or_404(Queue, name__iexact=qname, computer=comp.id)
            new_name = None
            for node in elem:
                tag_name = node.tag.lstrip('{http://cadac.sdsc.edu/schema/runtracker}')
                if(tag_name == 'Description'):
                    queue.description = node.text
                if(tag_name == 'Name'):
                    new_name = node.text

            if new_name:
                if new_name.lower() != qname:
                    return HttpResponse(status=400)

            queue.save()

        except:
            HttpResponse(status=400)

    if request.method == 'PUT':
        try:
            # make sure we can get the computer first
            comp = Computer.objects.get(name__iexact=compname)
        except:
            return HttpResponse('Can\'t create queue %s, Computer %s not found\n' %
                                (qname, compname), status=400)

        try:
            # get the xml data
            strlen = request.META['CONTENT_LENGTH']
            xml_str = request.META['wsgi.input'].read(strlen)
            try:
                elem = ET.fromstring(xml_str)
            except:
                return HttpResponse('Could not parse xml\n', status=400)

            new_name = new_comp_name = description = None
            for node in elem:
                tag_name = node.tag.lstrip('{http://cadac.sdsc.edu/schema/runtracker}')
                if(tag_name == 'Description'):
                    description = node.text
                if(tag_name == 'Name'):
                    new_name = node.text
                if(tag_name == 'Computer'):
                    new_comp_name = node.text

            if new_name.lower() != qname:
                return HttpResponse('Queue name %s does not match location %s' %
                                    (new_name, qname), status=400)

            if new_comp_name:
                if new_comp_name != comp.name:
                    return HttpResponse('Computer name %s does not match location %s' %
                                        (new_comp_name, comp.name), status=400)            
        
            new_queue = Queue.objects.create(name=new_name, computer=comp, 
                                               description=description)
        
        except:
            HttpResponse(status=400)

    return HttpResponse(status=200)
